<# 多行注释.........  
- [PowerShell教程](https://www.yiibai.com/powershell/)
- [终端上的文件管理器：lf-github的仓库地址](https://github.com/gokcehan/lf)
- [lf官方文档-英文](https://pkg.go.dev/github.com/gokcehan/lf)
#> 

<# 多行注释.........
# 函数: 函数格式
function [<scope:>]<name> [([type]$parameter1[,[type]$parameter2])]  
{  
  param([type]$parameter1 [,[type]$parameter2])  
  dynamicparam {<statement list>}  
  begin {<statement list>}  
  process {<statement list>}  
  end {<statement list>}  
}
#>

# 函数: 设置当前前端口为utf-8 的编码格式
function set-coding-format-utf8
{
    echo "set Coding Format UTF-8"
    chcp 65001
}

# 函数: 模板
function my-powershell-func  
{  
    echo "Windows Operating System" 
    Try  
    {  
        Get-ChildItem  
    }  
    catch  
    {  
        "Error in a Try block."  
    } 
}

# my-powershell-func
function which ($command) {
  Get-Command -Name $command -ErrorAction SilentlyContinue |
    Select-Object -ExpandProperty Path -ErrorAction SilentlyContinue
}

# 下载文件
function Invoke-Download
{
    param (
        [Parameter()] [string] $uri = "https://ftp.ncep.noaa.gov/data/nccf/com/hrrr/prod/hrrr.$m2/conus/hrrr.t$m21z.wrfsfcf00.grib2.idx",
        [Parameter()] [string] $outputPath = "C:\OpenGrADS-2.2\data\hrrr\test.grb2",
        [Parameter()] [int] $sleeptimer = 30,
        [Parameter()] [int] $maxTries = 3,
        [Parameter()] [int] $tries = 0
    )

    # 判断是否下载完成存在文件，存在则则不重复下载
    $TRUE_FALSE=(Test-Path $outputPath)
    if($TRUE_FALSE -eq "True")
    {
        # 文件已经存在
        echo "[Info] $outputPath is exits." 
    } else {
        try
        {
            Invoke-WebRequest -Uri $uri -OutFile $outputPath;
        }
        catch [System.Net.WebException]
        {
            $tries++;

            if($tries -lt $maxTries)
            {
                Start-Sleep -Seconds $sleeptimer
                Invoke-Download -uri $uri -outputPath $outputPath -sleeptimer $sleeptimer -maxTries $maxTries -tries $tries
            }
            else
            {
                Write-Error ("Tried to download '{0}' {1}-times and failed" -f $uri, $tries);
            }
        }   
    }
}



#  函数: 设置文件链接
function make-file-link-func($origin_target_file_path, $local_target_file_path)
{
    echo "[debug] origin_target_file_path = $origin_target_file_path"
    echo "[debug] local_target_file_path = $local_target_file_path"
    # 判断是否下载完成存在文件，存在则进行解压
    $TRUE_FALSE=(Test-Path $origin_target_file_path)
    if($TRUE_FALSE -eq "True") { 
        # 文件存在
        echo "[debug] It is exits."
        remove-Item -Recurse -Force $origin_target_file_path
    } else {
        # 文件不存在
        echo "[debug] It is not exits."
    }
    # 设置文件硬链接命令
    $cmd_string="cmd /C mklink /H $origin_target_file_path $local_target_file_path"
    echo echo "[debug] cmd_string = $cmd_string"
    # 执行命令
    Invoke-Expression $cmd_string
}


# 添加环境变量
# [如何在PowerShell中查找、添加、修改和删除环境变量：解决手动设置环境变量后报命令失效的问题_powershell 查看环境变量-CSDN博客](https://blog.csdn.net/Da_zhenzai/article/details/130238775)
function add-env-value($env_class,$env_name,$env_path) {
    # $existingPath = [Environment]::GetEnvironmentVariable("Path", "Machine")
    $existingPath = [Environment]::GetEnvironmentVariable($env_name, $env_class)
    # $newPath = $existingPath + ";C:\Program Files\MyApp"
    $newPath = $existingPath + ";$env_path"
    # [Environment]::SetEnvironmentVariable("Path", $newPath, "Machine")
    [Environment]::SetEnvironmentVariable($env_name, $newPath, $env_class)
    # 首先获取当前的PATH环境变量值，然后将C:\Program Files\MyApp添加到末尾，并使用SetEnvironmentVariable方法将新的值设置回环境变量中。
    # 注需要使用管理员权限
}

# 函数:流程控制函数
function process-control-main()
{  
    # 打印当前系统时间
    echo $(date)
    echo "Start Runing..."
    # 此处是你的代码

    # 1.开启允许命令行执行脚本的权限(以管理员身份运行)
    # set-executionpolicy -executionpolicy unrestricted 

    # 设置文件链接
    # vim的vimr配置
    $origin_target_file_path = "$HOME\_vimrc"
    $local_target_file_path = "$PSScriptRoot\vim\vimrc-simple"

    # vim的.vim配置
    $(make-file-link-func  "$HOME\.vim" "$PSScriptRoot\vim\.vim")

    # 打印当前系统时间
    echo $(date)
    echo "The End."
}

# -----------------------------------------------------------------------------
# 设置当前前端口为utf-8 的编码格式
set-coding-format-utf8
# 获取当前脚本位置
$ShellPath=$PSScriptRoot
echo "[Debug] ShellPath = $ShellPath"

# 获取当前脚本Shell本身的文件名
# $ShellFileName=$($MyInvocation.InvocationName)
# echo "[Debug] ShellFileName = $ShellFileName"

# 获取路径最后一部分
# $ShellFileName=$(Split-Path -Path $PSScriptRoot -Leaf)
# echo "[Debug] ShellFileName = $ShellFileName"

$flag=1
#$flag=0
if($flag)
{
    # echo "执行流程控制函数"
    echo "process-control-main"
    # process-control-main >> $ShellFileName".log"
    process-control-main
} else 
{
    # echo "执行测试单元函数"
    # my-powershell-func >> debug.log


    # add-env-value "Machine" "Path" "C:\Program Files\MyApp2"
    # 添加环境变量  系统环境变量 变量名 变量值

}
